﻿using CacheManager.Core;
using System;
using System.Collections.Generic;


namespace Kele.Repository.Utils
{
     public  class CacheUtils
    {
        private readonly ICacheManager<Process> _cacheManager;
        public CacheUtils(ICacheManager<Process> cacheManager)
        {
            _cacheManager = cacheManager;
        }

        public class Process
        {
            public int Total { get; set; }
            public int Current { get; set; }
            public string Message { get; set; }
        }

      
        private static string GetProcessCacheKey(string guid)
        {
            return $"ss:{nameof(Process)}:{guid}";
        }

        public void SetProcess(string guid, string message)
        {
            if (string.IsNullOrEmpty(guid)) return;

            //var cache = CacheUtils.Get<Process>(guid);
            var cacheKey = GetProcessCacheKey(guid);
            var process = _cacheManager.Get(cacheKey);
            if (process == null)
            {
                process = new Process
                {
                    Total = 100,
                    Current = 0,
                    Message = message
                };
            }
            else
            {
                process.Total++;
                process.Current++;
                process.Message = message;
            }

            var cacheItem = new CacheItem<Process>(cacheKey, process, ExpirationMode.Sliding, TimeSpan.FromHours(1));

            _cacheManager.AddOrUpdate(cacheItem, _ => process);

            //CacheUtils.InsertHours(guid, cache, 1);
        }

        public Process GetProcess(string guid)
        {
            var cacheKey = GetProcessCacheKey(guid);
            var process = _cacheManager.Get(cacheKey) ?? new Process
            {
                Total = 100,
                Current = 0,
                Message = string.Empty
            };

            return process;
        }

  
    }
}
